package com.xinyue.cross.server.server;

import com.xinyue.cross.server.server.handler.NettyDecoderHandler;
import com.xinyue.cross.server.server.handler.NettyEncodeHandler;
import com.xinyue.cross.server.server.handler.NettyHeartbeatHandler;
import com.xinyue.cross.server.server.handler.NettyLogicMessageHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

/**
 * netty socket 长连接的channel初始化工具，如果是开发tcp长连接游戏，使用这个channel初始化器
 *
 * @Author 王广帅
 * @Date 2021/1/24 17:20
 */
public class SocketServerChannelInitializer extends ChannelInitializer<Channel> {

    private Logger logger = LoggerFactory.getLogger(SocketServerChannelInitializer.class);
    private ApplicationContext context;
    private IHandlerMessageListener handlerMessageListener;


    public SocketServerChannelInitializer(ApplicationContext context, IHandlerMessageListener handlerMessageListener) {
        this.context = context;
        this.handlerMessageListener = handlerMessageListener;
    }

    @Override
    protected void initChannel(Channel ch) {
        try {
            XinyueCrossServerConfig gameFrameworkConfig = context.getBean(XinyueCrossServerConfig.class);
            ChannelPipeline p = ch.pipeline();
            p.addLast(new IdleStateHandler(0, 0, 0));
            // 添加拆包
            p.addLast(new LengthFieldBasedFrameDecoder(gameFrameworkConfig.getMaxFrameLength(), 0, 4, -4, 0));
            // 添加接收消息的解码handler
            p.addLast(new NettyDecoderHandler());
            p.addLast(new NettyEncodeHandler());
            p.addLast(new NettyHeartbeatHandler());
            p.addLast(new NettyLogicMessageHandler(handlerMessageListener));

        } catch (Throwable e) {
            logger.error("初始始化socket channel异常", e);
        }
    }

}
